package com.juguo.charginganimation.View.fragment;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.juguo.charginganimation.Base.BaseFragment;
import com.juguo.charginganimation.MainApplication;
import com.juguo.charginganimation.R;
import com.juguo.charginganimation.View.gallery.GallerDetailMake;
import com.juguo.charginganimation.View.gallery.GalleryDetailYyds;
import com.juguo.charginganimation.utils.ToastUtil;
import com.juguo.charginganimation.utils.UITools;
import com.juguo.charginganimation.Viewmodel.MakeViewModel;
import com.juguo.charginganimation.databinding.MakeFragmentBinding;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.List;

import pl.droidsonroids.gif.GifImageView;

public class MakeFragment extends BaseFragment implements View.OnClickListener {

    private MakeViewModel mViewModel;
    private MakeFragmentBinding binding;
    private ImageButton cddhzzImageBtn;
    private ImageButton imageButtonZzcd;
    private GifImageView imageViewGall;
    private AppCompatImageView appCompatImageView;
    private static final int REQUEST_CODE = 1024;

    public static MakeFragment newInstance() {
        return new MakeFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.make_fragment, container, false);
        return binding.getRoot();
    }

    @Override
    protected int initLayout() {
        return R.layout.make_fragment;
    }

    @Override
    protected void initView(View view) {

    }

    @Override
    protected void initData(Context mContext) {

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(MakeViewModel.class);
        cddhzzImageBtn = getActivity().findViewById(R.id.cddhzz_image_btn);
        cddhzzImageBtn.setOnClickListener(this::onClick);
        appCompatImageView = getActivity().findViewById(R.id.app_image_view_delet);
        appCompatImageView.setOnClickListener(this::onClick);
        imageViewGall = getActivity().findViewById(R.id.tupianxuanz_imv);
        imageButtonZzcd = getActivity().findViewById(R.id.imageButton_zzcd);
        imageButtonZzcd.setOnClickListener(this::onClick);
        //修复标题栏与状态栏重叠
        UITools.fitTitleBar(getActivity(), getView());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cddhzz_image_btn:
//                getImageFormGallery(getActivity(), imageViewGall);
                //申请权限部分
                String write = Manifest.permission.WRITE_EXTERNAL_STORAGE;
                String read = Manifest.permission.READ_EXTERNAL_STORAGE;
                final String[] WriteReadPermission = new String[]{write, read};
                int checkWrite = ContextCompat.checkSelfPermission(getContext(), write);
                int checkRead = ContextCompat.checkSelfPermission(getContext(), read);
                int ok = PackageManager.PERMISSION_GRANTED;
                if (checkWrite != ok && checkRead != ok) {
                    //申请权限，读和写都申请一下，不然容易出问题
                    ActivityCompat.requestPermissions(getActivity(), WriteReadPermission, 1);
                    cddhzzImageBtn.setVisibility(View.VISIBLE);
//                    openAlbum();
                } else {
                    openAlbum();
                    cddhzzImageBtn.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.app_image_view_delet:
                imageViewGall.setImageDrawable(null);
                cddhzzImageBtn.setVisibility(View.VISIBLE);
                imageButtonZzcd.setVisibility(View.GONE);
                break;
            case R.id.imageButton_zzcd:
                ToastUtil.showToast(MainApplication.getsInstance(), "应用成功！");
                //删除sp
                File file = new File("/data/data/" + getActivity().getPackageName().toString() + "/shared_prefs", "ImageYydsSc.xml");
                if (file.exists()) {
                    file.delete();
                }
                File ImageYyds = new File("/data/data/" + getActivity().getPackageName().toString() + "/shared_prefs", "ImageYyds.xml");
                if (ImageYyds.exists()) {
                    ImageYyds.delete();
                }
                Intent intentYyds = new Intent(getContext(), GallerDetailMake.class);
                intentYyds.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  //只启动一个实例
                startActivity(intentYyds);
                break;
        }
    }

    void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        //把所有照片显示出来
        intent.setType("image/*");
        startActivityForResult(intent, 123);
        cddhzzImageBtn.setVisibility(View.GONE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openAlbum();
        } else {
            ToastUtil.showToast(getContext(), "你拒绝了打开相册的权限");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //当选择完相片，就会回到这里，然后相片的相关信息会保存在data中，后面想办法取出来
        if (requestCode == 123) {

            //通过getData方法取得它的图片地址，后面的操作都是对这个地址的解析
            Uri uri = data.getData();
            //选择了一张在相册中id为26的照片，它的uri地址如下：
//            uri=content://com.android.providers.media.documents/document/image%3A26

            if (DocumentsContract.isDocumentUri(getContext(), uri)) {
                //判断是document类型的图片，所以获取它的doc id
                String docId = DocumentsContract.getDocumentId(uri);//docId=image:26
                //docId是将该资源的关键信息提取出来，比如该资源是一张id为26的image
                //获取它的uri的已解码的授权组成部分，来判断这张图片是在相册文件夹下还是下载文件夹下
                String uri_getAuthority = uri.getAuthority();
                //在相册文件夹的照片标识字段如下
                //uri_getAuthority=com.android.providers.media.documents
                //注意这里的字符串很容易写错，providers和documents都是有带s的
                if ("com.android.providers.media.documents".equals(uri_getAuthority)) {
                    //当判断该照片在相册文件夹下时，使用字符串的分割方法split将它id取出来
                    String id = docId.split(":")[1];//id="26"
                    Uri baseUri = Uri.parse("content://media/external/images/media");
                    imageViewGall.setImageURI(Uri.withAppendedPath(baseUri, id));
                    imageButtonZzcd.setVisibility(View.VISIBLE);
                    SharedPreferences sp = MainApplication.getsInstance().getSharedPreferences("ImageZzdh", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("coverImgUrlZzdh", String.valueOf(Uri.withAppendedPath(baseUri, id))).apply();
                }
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}